const gulp = require('gulp');
const ts = require('gulp-typescript');
const cls = require("gulp-clean")
const uglify = require('gulp-uglify-es').default
const es = require('event-stream')
const filter = require('gulp-filter')
const tsProject = ts.createProject('tsconfig.json');
const run = require("gulp-run");
const { parallel } = require('gulp');

function chown(cb) {
    return run("sudo chown ubuntu ./pkg/* -R").exec()
}
function clean(cb) {
    return gulp.src(["./dist/*.*", "./dist/*", "./pkg/etc/*", "./pkg/etc", "./pkg/usr/*", "./pkg/usr"], { allowEmpty: true })
        .pipe(cls());
}
function compile() {
    let tsResult = tsProject.src()
        .pipe(tsProject());
    return es.merge(
        tsResult.dts,
        tsResult.js.pipe(uglify({ compress: true }))
    ).pipe(gulp.dest('./dist'));
};
function compileDev() {
    let tsResult = tsProject.src()
        .pipe(tsProject());
    return tsResult.pipe(gulp.dest('./dist'));
};
function copyCert(cb) {
    return gulp.src("./src/certs/*.pem")
        .pipe(gulp.dest("./pkg/etc/ssl/certs"))
}
function copyKey(cb) {
    return gulp.src("./src/certs/*.key")
        .pipe(gulp.dest("./pkg/etc/ssl/private"))
}
function copyexe(cb) {
    return gulp.src("./dist/middleware")
        .pipe(gulp.dest("./pkg/usr/sbin"))
}
function copycfg(cb) {
    return gulp.src("./src/config/*.json")
        .pipe(gulp.dest("./pkg/etc/agilor"))
}
function copyservice(cb) {
    return gulp.src("./src/config/middleware.service")
        .pipe(gulp.dest("./pkg/etc/systemd/system"))
}
function runpkg(cb) {
    return run("pkg -t node18-linux-x64 ./dist/index.js -o ./dist/middleware").exec();
}
function chown_root(cb) {
    return run(`sudo chown root ./pkg/etc -R &&
    sudo chgrp root ./pkg/etc -R &&
    sudo chown root ./pkg/usr -R &&
    sudo chgrp root ./pkg/usr -R &&
    sudo chmod 755 ./pkg/usr -R &&
    sudo chmod 755 ./pkg/etc -R &&
    sudo chmod 640 ./pkg/etc/ssl/private/mini-tiger.com.key`).exec();
}
function rundpkg(cb) {
    return run("sudo dpkg -b ./pkg ./dist/middleware.deb").exec();
}
exports.build = gulp.series(chown, clean, gulp.parallel(copyCert, copyservice, copycfg, copyKey, compileDev));
exports.pkg = gulp.series(chown, clean, gulp.parallel(copyCert, copyservice, copycfg, copyKey, compile), runpkg, copyexe, chown_root, rundpkg)
exports.clean = gulp.series(chown, clean)